package com.dream.mqpushserver.proxy;

import com.alibaba.fastjson.JSON;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

/**
 * interface proxy
 */
public class ClassTestProxy {


    public static <T> T  getProxy(final Class<T> clazz) throws IllegalAccessException, InstantiationException {

        return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("clazz name "+ clazz.getName());
                System.out.println("method name " + method.getName());
                Class<?>[] parameterTypes = method.getParameterTypes();
                System.out.println("params : " + JSON.toJSONString(args));
                Map<String, Object> map = new HashMap<>();
                Class<?>[] interfaces = new TestInterfaceImpl().getClass().getInterfaces();
                for (Class<?> anInterface : interfaces) {
                    map.put(anInterface.getName(), new TestInterfaceImpl());
                }

                Object tempClazz = map.get(clazz.getName());
                Method targetMethod = tempClazz.getClass().getMethod(method.getName(), parameterTypes);
                Object invoke = targetMethod.invoke(tempClazz, args);
                System.out.println(" invoke ... "+ invoke);

                return "hello, this server response .... ";
            }
        });
    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        TestInterface proxy = getProxy(TestInterface.class);
        System.out.println(proxy.sayHello("test"));
    }
}
